package com.mkjb.controller;

import com.mkjb.dto.ChangePasswordDto;
import com.mkjb.dto.UserFormDto;
import com.mkjb.dto.UserListDto;
import com.mkjb.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.validation.Valid;

/**
 * Created by DingJie on 2017/5/16.
 */
@Controller
@RequestMapping("/admin/user")
public class UserController {
    @Autowired
    private UserService service;

    @RequestMapping("/list.htm")
    public String userList(UserListDto listDto, Model model) {
        service.getList(listDto);
        model.addAttribute("listDto", listDto);
        return "/user/list";
    }

    //添加和编辑界面
    @RequestMapping("/edit.htm")
    public String edit(String uuid, Model model) {
        UserFormDto formDto = service.loadUserFromDto(uuid);
        model.addAttribute("formDto", formDto);
        return "user/edit";
    }

    //添加和编辑方法
    @RequestMapping(value = "/edit", method = RequestMethod.POST)
    public String edit(@ModelAttribute("formDto") @Valid UserFormDto formDto, BindingResult result) {
        if (result.hasErrors()) {
            return "user/edit";
        }
        service.edit(formDto);
        return "redirect:/admin/user/list.htm?edit=success";
    }

    //删除
    @RequestMapping(value = "/delete.htm", method = RequestMethod.POST)
    public String delete(String uuid) {
        service.delete(uuid);
        return "redirect:list.htm?delete=success";
    }

    //修改密码
    @RequestMapping(value = "/change_password.htm", method = RequestMethod.GET)
    public String changePassword(Model model) {
        model.addAttribute("formDto", new ChangePasswordDto());
        return "/user/change_password";
    }

    //添加和编辑方法
    @RequestMapping(value = "/edit_change_password", method = RequestMethod.POST)
    public String editChangePassword(@ModelAttribute("formDto") @Valid ChangePasswordDto formDto, BindingResult result) {
        if (result.hasErrors()) {
            return "user/change_password";
        }
        service.editChangePassword(formDto);
        return "redirect:/admin/user/list.htm?edit=success";
    }
}
